package sensor

import (
	"fmt"
	"log"
	"time"
)

// SmokeParser 烟雾传感器解析器
type SmokeParser struct {
	expectedLength int
}

func NewSmokeParser(dataLength int) *SmokeParser {
	return &SmokeParser{
		expectedLength: dataLength, // 根据协议应该是9字节
	}
}

func (p *SmokeParser) Validate(data []byte) bool {
	if len(data) != p.expectedLength {
		log.Printf("烟雾传感器数据长度错误: 期望%d字节, 实际%d字节", p.expectedLength, len(data))
		return false
	}
	
	// 检查起始位是否为0xFF
	if data[0] != 0xFF {
		log.Printf("烟雾传感器起始位错误: 期望0xFF, 实际0x%X", data[0])
		return false
	}
	
	// 检查命令位是否为0x86（读取传感器AD值）
	if data[1] != 0x86 {
		log.Printf("烟雾传感器命令位错误: 期望0x86, 实际0x%X", data[1])
		return false
	}
	
	// 计算校验和: 0xFF - (B1+B2+...+B7) + 1
	calculatedChecksum := byte(0)
	for i := 1; i < 8; i++ { // B1到B7（索引1-7）
		calculatedChecksum += data[i]
	}
	calculatedChecksum = 0xFF - calculatedChecksum + 1
	
	actualChecksum := data[8] // B9是校验和
	
	if calculatedChecksum != actualChecksum {
		log.Printf("烟雾传感器校验和错误: 计算值0x%X, 实际值0x%X", calculatedChecksum, actualChecksum)
		log.Printf("详细计算: 字节[1-7]和=0x%X, 校验计算=0x%X", calculatedChecksum+actualChecksum-1, calculatedChecksum)
		return false
	}
	
	//log.Printf("烟雾传感器校验和正确: 0x%X", calculatedChecksum)
	return true
}

func (p *SmokeParser) Parse(data []byte) (*SensorData, error) {
	if !p.Validate(data) {
		return nil, fmt.Errorf("invalid smoke sensor data format")
	}

	// 解析AD值: B3 * 256 + B4
	adHigh := uint16(data[2])  // B3: AD值高字节
	adLow := uint16(data[3])    // B4: AD值低字节
	adValue := adHigh*256 + adLow
	
	// 解析满量程值: B5 * 256 + B6（根据协议，这些字节可能为0）
	fullScaleHigh := uint16(data[4])  // B5
	fullScaleLow := uint16(data[5])   // B6
	fullScaleValue := fullScaleHigh*256 + fullScaleLow
	
	//log.Printf("烟雾传感器解析结果: AD值=%d, 满量程=%d", adValue, fullScaleValue)
	
	return &SensorData{
		SensorType: "smoke",
		Values: map[string]interface{}{
			"ad_value":          adValue,        // AD值
			"full_scale":        fullScaleValue, // 满量程值
			"ad_high":           data[2],        // AD值高字节
			"ad_low":            data[3],        // AD值低字节
			"full_scale_high":   data[4],        // 满量程高字节
			"full_scale_low":    data[5],        // 满量程低字节
		},
		RawData:   fmt.Sprintf("%X", data),
		Timestamp: time.Now(),
	}, nil
}